
/**
 * 标签页容器组件
 * @date 2025/11/20 11:53:17
 * @author lyqjob@yeah.net
 *
 * @returns {*} 
 */

import React, { useState, useCallback, useMemo } from 'react';
import { Tabs, Dropdown, message } from 'antd';
import { closestCenter, DndContext, PointerSensor, useSensor } from '@dnd-kit/core';
import {
    arrayMove,
    horizontalListSortingStrategy,
    SortableContext,
    useSortable,
    sortableKeyboardCoordinates
} from '@dnd-kit/sortable';
import { CSS } from '@dnd-kit/utilities';
import { restrictToHorizontalAxis } from '@dnd-kit/modifiers';
import {
    ReloadOutlined,
    CloseOutlined,
    CloseCircleOutlined,
} from '@ant-design/icons';
import useTabsManager from '../../hooks/useTabsManager';
import { IconMap } from '@/utils/iconUtils';
import './index.css';

const TabsContainer = () => {
    const {
        tabs,
        activeKey,
        tabItems,
        closeTab,
        closeOtherTabs,
        closeAllTabs,
        switchTab,
        refreshTab,
        reorderTabs
    } = useTabsManager();

    const [contextMenuVisible, setContextMenuVisible] = useState(false);
    const [contextMenuPosition, setContextMenuPosition] = useState({ x: 0, y: 0 });
    const [contextMenuTabKey, setContextMenuTabKey] = useState('');
    
    // 拖拽排序
    const sensor = useSensor(PointerSensor, { activationConstraint: { delay: 180, tolerance: 5 } });
    
    // 拖拽结束时调用
    const onDragEnd = ({ active, over }) => {
        if (active && over && active.id !== over.id) {
            // 调用 useTabsManager 的 reorderTabs 方法
            reorderTabs(active.id, over.id);
        }
    };

    // 处理标签页编辑（关闭）
    const handleEdit = useCallback((targetKey, action) => {
        if (action === 'remove') {
            closeTab(targetKey);
        }
    }, [closeTab]);

    // 右键菜单处理
    const handleContextMenu = useCallback((e, tabKey) => {
        e.preventDefault();
        e.stopPropagation();

        setContextMenuTabKey(tabKey);
        setContextMenuPosition({
            x: e.clientX,
            y: e.clientY
        });
        setContextMenuVisible(true);
    }, []);

    // 关闭右键菜单
    const closeContextMenu = useCallback(() => {
        setContextMenuVisible(false);
    }, []);

    // 右键菜单项处理
    const handleContextMenuClick = useCallback(({ key }) => {
        const tabKey = contextMenuTabKey;

        switch (key) {
            case 'refresh':
                refreshTab(tabKey);
                message.success('刷新成功');
                break;
            case 'close':
                closeTab(tabKey);
                break;
            case 'closeOthers':
                closeOtherTabs(tabKey);
                message.success('关闭其他标签页成功');
                break;
            case 'closeAll':
                closeAllTabs();
                message.success('关闭所有标签页成功');
                break;
            default:
                break;
        }

        closeContextMenu();
    }, [contextMenuTabKey, refreshTab, closeTab, closeOtherTabs, closeAllTabs, closeContextMenu]);

    // 右键菜单配置
    const contextMenuItems = useMemo(() => ([
        {
            key: 'refresh',
            label: '刷新',
            icon: <ReloadOutlined />
        },
        {
            type: 'divider'
        },
        {
            key: 'close',
            label: '关闭',
            icon: <CloseOutlined />,
            disabled: tabs.find(tab => tab.key === contextMenuTabKey)?.isPinned
        },
        {
            key: 'closeOthers',
            label: '关闭其他',
            icon: <CloseCircleOutlined />
        },
        {
            key: 'closeAll',
            label: '关闭所有',
            icon: <CloseCircleOutlined />
        }
    ]), [tabs, contextMenuTabKey]);


    const DraggableTabNode = ({ className, ...props }) => {
        const { attributes, listeners, setNodeRef, transform, transition, isDragging } = useSortable({
            id: props['data-node-key'],
        });
        const style = {
            ...props.style,
            transform: CSS.Translate.toString(transform),
            transition: isDragging ? 'none' : transition,
            cursor: isDragging ? 'grabbing' : 'move',
        };
        
        // 添加拖拽状态类名
        const tabClassName = isDragging ? `${className} dragging` : className;
        
        return React.cloneElement(props.children, {
            ref: setNodeRef,
            style,
            className: tabClassName,
            ...attributes,
            ...listeners,
        });
    };

    // 渲染标签页项
    const renderTabItem = useCallback((tab) => {
        
        return {
            ...tab,
            label: (
                <div
                    className="tab-label"
                    onContextMenu={(e) => handleContextMenu(e, tab.key)}
                >
                    {tab.icon ? IconMap[tab.icon] && <span className="tab-icon">{IconMap[tab.icon]}</span> : null}
                    <span className="tab-text">{tab.label}</span>
                </div>
            )
        };
    }, [handleContextMenu]);

    // 渲染的标签页项目
    const items = useMemo(() => tabItems.map(renderTabItem), [tabItems, renderTabItem]);
    const tabKeys = useMemo(() => tabItems.map(i => i.key), [tabItems]);
    const sensorsList = useMemo(() => [sensor], [sensor]);

    return (
        <>
            <Tabs
                type="editable-card"
                hideAdd
                activeKey={activeKey}
                onChange={switchTab}
                onEdit={handleEdit}
                items={items}
                renderTabBar={(tabBarProps, DefaultTabBar) => (
                    <DndContext 
                        sensors={sensorsList} 
                        onDragEnd={onDragEnd} 
                        collisionDetection={closestCenter}
                        modifiers={[restrictToHorizontalAxis]}
                    >
                        <SortableContext items={tabKeys} strategy={horizontalListSortingStrategy}>
                            <DefaultTabBar {...tabBarProps}>
                                {node => (
                                    <DraggableTabNode {...node.props} key={node.key}>
                                        {node}
                                    </DraggableTabNode>
                                )}
                            </DefaultTabBar>
                        </SortableContext>
                    </DndContext>
                )}
                className="tabs_container"
                size="small"
            />

            {/* 右键菜单 */}
            <Dropdown
                menu={{
                    items: contextMenuItems,
                    onClick: handleContextMenuClick
                }}
                trigger={['contextMenu']}
                open={contextMenuVisible}
                onOpenChange={closeContextMenu}
                placement="bottomLeft"
            >
                <div
                    className="context-menu-trigger"
                    style={{
                        position: 'fixed',
                        left: contextMenuPosition.x,
                        top: contextMenuPosition.y,
                        width: 1,
                        height: 1,
                        pointerEvents: contextMenuVisible ? 'auto' : 'none'
                    }}
                />
            </Dropdown>
        </>
    );
};

export default TabsContainer;